using System;
using System.Web;


namespace SiteECSWeb
{
    public class RefreshAction
    {
        #region MyRegion
        // Constants
        public const string LastRefreshTicketEntry = "__LASTREFRESHTICKET";
        public const string CurrentRefreshTicketEntry = "__CURRENTREFRESHTICKET";
        public const string PageRefreshEntry = "IsPageRefresh";
        #endregion


        // Manage to check if the F5 button has been pressed
        public static void Check(HttpContext context)
        {
            // Initialize the ticket slot
            EnsureRefreshTicket(context);

            // Read the last ticket served in the session (from Session)
            int lastTicket = GetLastRefreshTicket(context);

            // Read the ticket of the current request (from a hidden field)
            int thisTicket = GetCurrentRefreshTicket(context);

            // Compare tickets
            if (thisTicket > lastTicket ||
                (thisTicket == lastTicket && thisTicket == 0))
            {
                UpdateLastRefreshTicket(context, thisTicket);
                context.Items[PageRefreshEntry] = false;
            }
            else
            {
                context.Items[PageRefreshEntry] = true;
            }
        }

        // Ensure that the slot for the last ticket served isn't null
        private static void EnsureRefreshTicket(HttpContext context)
        {
            // Initialize the session slots for the page (Ticket) and the module (LastTicketServed)            
            
            if (context.Session[LastRefreshTicketEntry] == null)
            {
                context.Session[LastRefreshTicketEntry] = 0;
            }
        }

        // Return the ticket of the last request in the session
        private static int GetLastRefreshTicket(HttpContext context)
        {
            // Extract and return the last ticket
            return Convert.ToInt32(context.Session[LastRefreshTicketEntry]);
        }

        // Return the ticket of the last request in the session
        private static int GetCurrentRefreshTicket(HttpContext context)
        {
            return Convert.ToInt32(context.Request[CurrentRefreshTicketEntry]);
        }

        // Return the ticket of the last request in the session
        private static void UpdateLastRefreshTicket(HttpContext context, int ticket)
        {
            context.Session[LastRefreshTicketEntry] = ticket;
        }
    }
}
